<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" :isSearchDisabled="isSearchDisabled" @reset="clearSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[485]">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select style="width: 100%" @change="tenantChange" v-model="page.adminUserId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证')">
          <el-input v-model="page.idcard" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('还款交易流水')" label-width="110px" prop="phone">
          <el-input v-model="page.refundTurnover"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[486]">
        <el-form-item :label="$t('溢出类型')" prop="overflowType">
          <el-select style="width: 100%" v-model="page.overflowType" clearable>
            <el-option :value="1" :label="$t('还款')"></el-option>
            <el-option :value="2" :label="$t('展期')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('退款交易流水')" label-width="110px" prop="phone">
          <el-input v-model="page.returnTurnover"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[486]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('退款类型')">
          <el-select v-model="page.returnType" style="width: 100%" clearable>
            <el-option :label="$t('线上')" :value="1"></el-option>
            <el-option :label="$t('线下')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('退款状态')">
          <el-select v-model="page.returnStatus" style="width: 100%" clearable>
            <el-option v-for="item in orderStatusList" :label="item.label" :key="item.value"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('还款时间')" prop="returnTime">
          <el-date-picker
              v-model="page.returnTime"
              style="width: 100%"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('退款到账时间')" label-width="110px" prop="accountTime">
          <el-date-picker
              v-model="page.accountTime"
              style="width: 100%"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('溢出时间')">
          <el-date-picker
              v-model="page.overFlowTimeValue"
              style="width: 100%"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card shadow="never" style="margin-top: 10px">
      <el-row :gutter="24" style="margin: 0 0 10px 0 ;line-height: 32px;">
        <el-col v-show="$permiss[529]" :span="20">
          <el-link style="font-size: 18px;margin-right: 20px" type="primary" :underline="false">{{ $t('溢出总金额') }} :
            {{ amountTotal.overflowAmount }}
          </el-link>
          <el-link style="font-size: 18px" type="primary" :underline="false">{{ $t('退款总金额') }} :
            {{ amountTotal.returnAmount }}
          </el-link>
        </el-col>
        <el-col style="text-align: right;" v-show="$permiss[785]" :span="4">
          <el-button type="primary" @click="exportsExcel" :loading="exportsLoading">{{ $t('导出') }}</el-button>
        </el-col>
      </el-row>
      <Table :loading="loading" max-height="600px" :table-data="tableData" :table-column="tableColumn" :page="page"
             @handleCurrentChange="handleCurrentChange"
             @handleSizeChange="handleSizeChange">
        <template slot-scope="{row}" slot="handle">
          <div v-if="row.status !== $t('退款成功')">
            <el-button type="text" @click="tableRowsClick(row,'online')" v-show="$permiss[591]">{{
              $t('线上')
              }}
            </el-button>
            <el-button type="text" @click="tableRowsClick(row,'offline')" v-show="$permiss[484]">{{
              $t('线下')
              }}
            </el-button>
          </div>
        </template>
      </Table>
    </el-card>
    <!--     线上退款-->
    <Dialog :visible.sync="onlineVisible" :title="$t('线上退款')" :confirmLoading="onlineLoading"
            @cancel="onlineVisible = false" @confirm="onlineConfirm">
      <el-form label-width="80px">
        <el-form-item :label="$t('订单编号')">
          <div style="line-height: 32px">
            {{ tableRows.loanRecordId }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('用户姓名')">
          <div style="line-height: 32px">
            {{ tableRows.name }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('手机号码')">
          <div style="line-height: 32px">
            {{ tableRows.phone }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('退款金额')">
          <div style="line-height: 32px">
            {{ tableRows.overflowAmount }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('备注')">
          <el-input type="textarea" :rows="4" v-model="tableRows.remark"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    线下退款-->
    <Dialog :visible.sync="offlineVisible" :title="$t('线下退款')" @cancel="offlineVisible = false"
            :confirmLoading="offlineLoading"
            @close="clearForm"
            @confirm="offlineConfirm">
      <el-form ref="offlineForm" :model="offlineForm" label-width="80px">
        <el-form-item :label="$t('订单编号')">
          <div style="line-height: 32px">
            {{ tableRows.loanRecordId }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('用户姓名')">
          <div style="line-height: 32px">
            {{ tableRows.name }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('手机号码')">
          <div style="line-height: 32px">
            {{ tableRows.phone }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('退款金额')">
          <div style="line-height: 32px">
            {{ tableRows.overflowAmount }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('退款银行')" prop="returnChannel" :rules="[
         { required: true, message: $t('请选择打款银行'), }
        ]" v-if="$permiss[578]">
          <el-select v-model="offlineForm.returnChannel">
            <el-option v-for="item in backList" :key="item.alias" :label="item.alias"
                       :value="item.alias"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('交易流水')" prop="returnTurnover">
          <el-input v-model="offlineForm.returnTurnover"/>
        </el-form-item>
        <el-form-item :label="$t('退款时间')" prop="arriveTime" :rules="[
         { required: true, message: $t('请选择退款时间'), }
        ]">
          <el-date-picker
              :picker-options="pickerOptions"
              v-model="offlineForm.arriveTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('选择交易时间')"
          />
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input type="textarea" :rows="4" v-model="offlineForm.remark"/>
        </el-form-item>
      </el-form>

    </Dialog>
  </div>
</template>

<script>
import {dateFormatSection, deepClone, defaultTimeDate} from "@/utils/tools";
import {export_json_to_excel} from "@/utils/exportExcel";
import {selectTenant, selectProduct} from "@/api/system";
import {selectOverflowList, overExport, selectTotalAmount, onLineReimburse, doReimburse} from '@/api/finance'
import {fetchPayBank} from '@/api/pay'

export default {
  name: 'repaymentOverflow',
  data() {
    return {
      tenantList: [],
      productList: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        returnTime: defaultTimeDate(14)
      },
      orderStatusList: [
        {label: this.$t('待退款'), value: 0},
        {label: this.$t('已退款'), value: 21},
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      tableColumn: [
        {label: this.$t('订单编号'), fixed: "left", align: "center", prop: 'loanRecordId', minWidth: 150},
        {label: this.$t('用户姓名'), prop: 'name', minWidth: 150},
        {label: this.$t('手机号码'), prop: 'phone',},
        {label: this.$t('身份证'), prop: "idCard", align: "center", minWidth: 100,},
        {label: this.$t('APP名称'), prop: 'appName',},
        {label: this.$t('还款时间'), prop: 'refundTime', minWidth: 150},
        {label: this.$t('溢出时间'), prop: 'inputTime', minWidth: 150},
        {label: this.$t('已还金额'), prop: 'refundAmount',},
        {label: this.$t('还款交易流水'), prop: 'refundTurnover', minWidth: 150},
        {label: this.$t('溢出金额'), prop: 'overflowAmount',},
        {label: this.$t('溢出类型'), prop: 'overflowType',},
        {label: this.$t('退款金额'), prop: 'returnAmount',},
        {label: this.$t('退款交易流水'), prop: 'returnTurnover', minWidth: 150},
        {label: this.$t('退款类型'), prop: 'returnType',},
        {label: this.$t('退款渠道'), prop: 'returnChannel', minWidth: 150},
        {label: this.$t('退款操作员'), prop: 'operatingName', minWidth: 150},
        {label: this.$t('备注'), prop: 'remark', minWidth: 200},
        {label: this.$t('退款发起时间'), prop: 'sendTime', minWidth: 150},
        {label: this.$t('退款到账时间'), prop: 'arriveTime', minWidth: 150},
        {label: this.$t('退款状态'), prop: 'status',},
        {label: this.$t('失败原因'), prop: 'failure_message',},
        {
          label: this.$t('操作'),
          fixed: "right",
          align: "center",
          slot: 'handle',
          width: 150,
          isHide: !this.$permiss[591] && !this.$permiss[484]
        }
      ],
      tableData: [],
      loading: false,
      amountTotal: {
        overflowAmount: 0,
        returnAmount: 0
      },
      tableRows: {},
      onlineVisible: false,
      onlineLoading: false,
      offlineVisible: false,
      offlineLoading: false,
      offlineForm: {},
      backList: [],
      exportsLoading: false,
      isSearchDisabled: false
    }
  },
  async mounted() {
    this.getTableData()
    selectTenant().then(res => {
      this.tenantList = res.data
    })
    selectProduct().then(res => {
      this.productList = res.data
    })
  },
  methods: {
    async getTableData() {
      this.loading = true
      this.isSearchDisabled = true
      const [arriveStartTime, arriveEndTime] = dateFormatSection(this.page.accountTime || [])
      const [refundStartTime, refundEndTime] = dateFormatSection(this.page.returnTime || [])
      const [overflowStartTime, overflowEndTime] = dateFormatSection(this.page.overFlowTimeValue || [])
      const params = {
        ...this.page,
        arriveStartTime, arriveEndTime,
        overflowStartTime, overflowEndTime,
        refundStartTime, refundEndTime
      }
      delete params.accountTime
      delete params.returnTime
      delete params.overFlowTimeValue
      this.getAmountTotal(params)
      const res = await selectOverflowList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          item.status = item.status === 0 ? this.$t('待退款') : item.status === 11 ? this.$t('退款中') : this.$t('退款成功')
          item.returnType = item.returnType === 1 ? this.$t('线上') : item.returnType === 2 ? this.$t('线下') : ''
          item.overflowType = item.overflowType === 1 ? this.$t('还款') : item.overflowType === 2 ? this.$t('展期') : ''
          return item
        })
        this.page.total = total
        this.loading = false
        this.isSearchDisabled = false
      } else {
        this.loading = false
        this.isSearchDisabled = false
      }
    },
    async getAmountTotal(params) {
      if (this.$permiss[529]) {
        const res = await selectTotalAmount(params)
        if (res.code === 1) {
          this.amountTotal = res.data
        }
      }
    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page,'productName', null)
      })
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    tableRowsClick(row, type) {
      this.tableRows = deepClone(row)
      if (type === 'offline') {
        this.offlineRefund()
      } else {
        this.onlineRefund()
      }
    },
    //线上退款
    onlineRefund() {
      this.onlineVisible = true
    },
    // 线下退款
    async offlineRefund() {
      const {adminUserId, productName} = this.tableRows
      this.backList = await fetchPayBank({adminUserId, productName}).then(res => res.data)
      if (this.backList && this.backList.length) {
        this.$set(this.offlineForm, 'returnChannel', this.backList[0].alias)
      }
      this.offlineVisible = true
    },
    // 线上退款提交
    async onlineConfirm() {
      this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
        type: "warning",
      }).then(async () => {
        this.onlineLoading = true
        const {overflowAmount, loanRecordId, id, remark} = this.tableRows
        const res = await onLineReimburse({
          returnAmount: overflowAmount,
          loanRecordId,
          id,
          remark
        })
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.onlineLoading = false
          this.onlineVisible = false
          this.getTableData()
        } else {
          this.onlineLoading = false
        }
      }).catch(() => {
      });
    },
    //线下退款提交
    async offlineConfirm() {
      this.$refs.offlineForm.validate(async v => {
        if (v) {
          this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
            type: "warning",
          }).then(async () => {
            this.offlineLoading = true
            const {overflowAmount, loanRecordId, id} = this.tableRows
            const res = await doReimburse({
              returnAmount: overflowAmount,
              loanRecordId,
              id,
              ...this.offlineForm
            })
            if (res.code === 1) {
              this.$message.success(this.$t('操作成功'))
              this.offlineVisible = false
              this.offlineLoading = false
              this.getTableData()
            } else {
              this.offlineLoading = false
            }
          }).catch(() => {
          });
        }
      })
    },
    clearForm() {
      this.offlineForm = {}
      this.$refs.offlineForm.resetFields()
    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const [arriveStartTime, arriverEndTime] = dateFormatSection(this.page.accountTime || [])
      const [refundStartTime, refundEndTime] = dateFormatSection(this.page.returnTime || [])
      const [overflowStartTime, overflowEndTime] = dateFormatSection(this.page.overFlowTimeValue || [])
      const params = {
        ...this.page,
        arriveStartTime, arriverEndTime,
        overflowStartTime, overflowEndTime,
        refundStartTime, refundEndTime
      };
      delete params.accountTime
      delete params.returnTime
      delete params.overFlowTimeValue
      const res = await overExport(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          item.status = item.status === 0 ? this.$t('待退款') : item.status === 11 ? this.$t('退款中') : this.$t('退款成功')
          item.returnType = item.returnType === 1 ? this.$t('线上') : item.returnType === 2 ? this.$t('线下') : ''
          return item
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("还款溢出表");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
  }
}
</script>

<style scoped>

</style>
